package fr.obsmip.sedoo.client.ui.table.news;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;

import fr.obsmip.sedoo.client.ui.WelcomeView.Presenter;
import fr.obsmip.sedoo.client.ui.table.summary.SummaryClickHandler;
import fr.obsmip.sedoo.client.ui.table.summary.SummaryRenderer;
import fr.obsmip.sedoo.shared.domain.MetadataUpdateNewDTO;
import fr.obsmip.sedoo.shared.domain.SummaryDTO;
import fr.sedoo.commons.client.news.widget.DefaultTitledMessageRenderer;
import fr.sedoo.commons.shared.domain.New;
import fr.sedoo.commons.shared.domain.message.TitledMessage;

public class NewsCell extends AbstractCell<New>
{

	private Presenter presenter;
	private String language;
	private DefaultTitledMessageRenderer renderer = new DefaultTitledMessageRenderer();

	public NewsCell(String language)
	{
		// On ecoute seulement les click éventuels sur les boutons
		super("click");
		this.language = language;
	}

	@Override
	public void render(Context context, New value, SafeHtmlBuilder sb)
	{
		if (value == null)
		{
			return;
		}
		if (value instanceof MetadataUpdateNewDTO)
		{
			SummaryRenderer.render(context, ((MetadataUpdateNewDTO) value).getSummaryDTO(), sb);
		}
		else if (value instanceof TitledMessage)
		{
			renderer.render(context, (TitledMessage) value, sb, language);
		}
		else
		{
			return;
		}
	}

	@Override
	public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context, Element parent, New value, NativeEvent event, ValueUpdater<New> valueUpdater)
	{
		super.onBrowserEvent(context, parent, value, event, valueUpdater);
		EventTarget eventTarget = event.getEventTarget();
		if (Element.is(eventTarget))
		{
			Element src = Element.as(eventTarget);

			if (value instanceof MetadataUpdateNewDTO)
			{
				SummaryDTO summaryDTO = ((MetadataUpdateNewDTO) value).getSummaryDTO();
				SummaryClickHandler.handleClick(src, summaryDTO, getPresenter());
			}
		}
	}

	private Presenter getPresenter()
	{
		return presenter;
	}

	public void setPresenter(Presenter presenter)
	{
		this.presenter = presenter;
	}

}
